import React, { Component } from 'react';
// import "@/styles/CountDown.scss"
import "../styles/CountDown.scss"

class CountDown extends Component {
    constructor(props){
        super(props);
        this.state = { 
            hour:2,minutes:0,seconds:0
        }
    }
    addZero(num){
        return num < 10 ? ('0' + num) : num;
    }
    componentDidMount(){
        this.timerid = setInterval(()=>{
            //秒数减1
            this.state.seconds = this.state.seconds - 1;
            
            if( this.state.seconds < 0 ){
                //如果秒数小于0,秒数设置为59,分钟减1
                this.state.seconds = 59;
                this.state.minutes = this.state.minutes-1;
                
                if( this.state.minutes < 0 ){
                    //如果分钟小于0,分钟设置为59,小时减1
                    this.state.minutes = 59;
                    this.state.hour = this.state.hour-1;

                    if( this.state.hour == -1 ){
                        clearInterval( this.timerid )
                    }
                }
            }

            //每隔1s更新一次组件的状态值,触发组件更新
            this.setState({ hour: this.state.hour, minutes: this.state.minutes, seconds: this.state.seconds })
        },1000)
    }
    render() {
        return (
            <span className='countdown'>
                <span className='num'>{this.addZero( this.state.hour )}</span>
                <span className='num'>{this.addZero( this.state.minutes )  }</span>
                <span className='num'>{this.addZero( this.state.seconds )}</span>
            </span>
        );
    }
}

export default CountDown;